package com.xzsoft.gdwz.jwt.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class JwtHelper {
	
	private static final String base64Security="gdwz2016.";
	
	
	public static Claims parseJWT(String jsonWebToken){
		try
		{
			Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security)).parseClaimsJws(jsonWebToken).getBody();
			return claims;
		}
		catch(Exception ex)
		{
			return null;
		}
	}
	
	public static String createJWT(String username, String password,String timestamp,String macAddress,String sign,
			String audience, String issuer,long TTLMillis) 
	{
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		//生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		  //添加构成JWT的参数
		JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT")
										.claim("username", username)
				                        .claim("password", password)
				                        .claim("timestamp", timestamp)
				                        .claim("macAddress", macAddress)
				                        .claim("sign", sign)
				                        .setIssuer(issuer)
				                        .setAudience(audience)
				                        .setSubject(username)
		                                .signWith(signatureAlgorithm, signingKey);
		 //添加Token过期时间
		if (TTLMillis >= 0) {
		    long expMillis = nowMillis + TTLMillis;
		    Date exp = new Date(expMillis);
		    builder.setExpiration(exp).setNotBefore(now);
		}
		 //生成JWT
		return builder.compact();
	}
	
	public static void main(String[] args){
		Claims claims = parseJWT(null);
		System.out.println(claims);
	}
}
